<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'

const cartList = ref<any[]>([])
const userId = localStorage.getItem('userId') || '1' // TODO: 替换为实际用户ID
const search = ref('')

// 多选相关
const selectedIds = ref<string[]>([])
const isAllSelected = computed(() => cartList.value.length > 0 && selectedIds.value.length === cartList.value.length)
const toggleSelect = (id: string) => {
  if (selectedIds.value.includes(id)) {
    selectedIds.value = selectedIds.value.filter(_id => _id !== id)
  } else {
    selectedIds.value.push(id)
  }
}
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = cartList.value.map(item => item._id)
  }
}
// 批量删除
const batchDelete = async () => {
  if (selectedIds.value.length < 1) {
    alert('请至少选择一个商品')
    return
  }
  if (!confirm(`确定要删除选中的${selectedIds.value.length}项吗？`)) return
  try {
    const res = await axios.delete('http://localhost:3000/ss/cart', { data: { ids: selectedIds.value } })
    if (res.data.code === 0) {
      cartList.value = cartList.value.filter(item => !selectedIds.value.includes(item._id))
      selectedIds.value = []
    } else {
      alert(res.data.msg || '批量删除失败')
    }
  } catch (e) {
    alert('批量删除失败')
  }
}

// 删除弹窗相关
const showDeleteModal = ref(false)
const itemToDelete = ref<any>(null)
const modalNum = ref(1)
const modalPrice = ref(0)
const modalIndex = ref(-1)

const onDeleteClick = (item: any) => {
  itemToDelete.value = item
  modalNum.value = item.num
  modalPrice.value = item.price
  modalIndex.value = cartList.value.findIndex(i => i._id === item._id)
  showDeleteModal.value = true
}
const changeModalNum = (delta: number) => {
  let newNum = Number(modalNum.value) + delta
  if (newNum < 1) newNum = 1
  if (newNum > 99) newNum = 99
  modalNum.value = newNum
  // 实时同步到主列表
  if (modalIndex.value !== -1) {
    cartList.value[modalIndex.value].num = newNum
  }
}
const confirmDelete = async () => {
  if (itemToDelete.value) {
    // 先请求后端删除
    try {
      const res = await axios.delete(`http://localhost:3000/ss/cart/${itemToDelete.value._id}`)
      if (res.data.code === 0) {
        cartList.value = cartList.value.filter(i => i._id !== itemToDelete.value._id)
        selectedIds.value = selectedIds.value.filter(id => id !== itemToDelete.value._id)
      } else {
        alert(res.data.msg || '删除失败')
      }
    } catch (e) {
      alert('删除失败')
    }
  }
  showDeleteModal.value = false
  itemToDelete.value = null
  modalIndex.value = -1
}
const cancelDelete = () => {
  showDeleteModal.value = false
  itemToDelete.value = null
  modalIndex.value = -1
}

// 获取购物车数据
const fetchCart = async () => {
  const res = await axios.get('http://localhost:3000/ss/cart', { params: { userId, search: search.value } })
  if (res.data.code === 0) {
    cartList.value = res.data.data
  }
  console.log(cartList.value);
  
}

// 搜索防抖
let searchTimer: any = null
watch(search, () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    fetchCart()
  }, 300)
})

// 计算总价
const totalPrice = computed(() =>
  cartList.value
    .filter(item => selectedIds.value.includes(item._id))
    .reduce((sum, item) => sum + (Number(item.price || 0) * Number(item.num || 0)), 0)
)

// 数量加减
const changeNum = (item: any, delta: number) => {
  let newNum = Number(item.num) + delta
  if (newNum < 1) newNum = 1
  if (newNum > 99) newNum = 99
  item.num = newNum
  // TODO: 可在此处调用后端接口同步数量
}

const showSuccessModal = ref(false)
const showClearConfirm = ref(false)

const handleClearSelected = async () => {
  try {
    // 调用后端批量删除接口
    const res = await axios.delete('http://localhost:3000/ss/cart', { data: { ids: selectedIds.value } })
    if (res.data.code === 0) {
      // 接口调用成功后更新前端数据
      cartList.value = cartList.value.filter(item => !selectedIds.value.includes(item._id))
      selectedIds.value = []
    } else {
      alert(res.data.msg || '清空已结算商品失败')
    }
  } catch (e) {
    alert('清空已结算商品失败，请重试')
  }
  showClearConfirm.value = false
}

const handleCancelClear = () => {
  selectedIds.value = [] // 清空选中状态
  showClearConfirm.value = false
}

const checkout = async () => {
  if (selectedIds.value.length < 1) {
    alert('请至少选择一个商品结算')
    return
  }
  const items = cartList.value
    .filter(item => selectedIds.value.includes(item._id))
    .map(item => ({
      shopId: item.shopId,
      colorx: item.colorx,
      chima: item.chima,
      num: item.num
    }))
  try {
    const res = await axios.post('http://localhost:3000/ss/order', {
      userId,
      items
    })
    if (res.data.code === 0) {
      showSuccessModal.value = true // 显示订单成功弹窗
      //
      //跳转到订单页面
      setTimeout(() => {
        window.location.href = '/OrderConfirmed1'
      }, 2000) // 2秒后跳转到订单页面
    } else {
      alert(res.data.msg || '结算失败')
    }
  } catch (e) {
    alert('结算失败')
  }
}

onMounted(() => {
  fetchCart()
})
</script>

<template>
  <div class="cart">
    <!-- 工具栏：全选和批量删除 -->
    <div class="cart-toolbar">
      <input type="checkbox" :checked="isAllSelected" @change="toggleSelectAll" /> 全选
      <button class="batch-delete" :disabled="selectedIds.length < 1" @click="batchDelete">批量删除</button>
    </div>
    <!-- 搜索框 -->
    <div class="search-bar">
      <input
        type="text"
        placeholder="搜索"
        v-model="search"
      />
    </div>
    <!-- 商品列表 -->
    <div class="cart-list">
      <div class="cart-item" v-for="item in cartList" :key="item._id">
        <input type="checkbox" :checked="selectedIds.includes(item._id)" @change="toggleSelect(item._id)" />
        <div class="item-img">
          <img :src="item.images" alt="商品图片" />
        </div>
        <div class="item-info">
          <div class="item-title">{{ item.name || '商品名称' }}</div>
          <div class="item-attr">
            <span class="color-dot"></span>
            <span>{{ item.colorx }}</span>
            <span class="attr-gap">{{ item.chima }}</span>
          </div>
          <div class="item-price">
            ¥{{ item.price * item.num }}
          </div>
        </div>
        <div class="item-actions">
          <button class="btn-action" @click="changeNum(item, -1)">-</button>
          <span>{{ item.num }}</span>
          <button class="btn-action" @click="changeNum(item, 1)">+</button>
        </div>
        <div class="item-delete" @click="onDeleteClick(item)">🗑️</div>
      </div>
    </div>
    <!-- 底部结算栏 -->
    <div class="cart-footer">
      <div class="total">
        <div class="total-label">合计</div>
        <div class="total-price">¥{{ totalPrice }}</div>
      </div>
      <button class="checkout" @click="checkout">结算</button>
    </div>
    <!-- 订单成功弹窗 -->
<div v-if="showSuccessModal" class="modal-mask">
  <div class="modal-content">
    <div class="modal-title">订单生成成功</div>
    <div class="modal-actions">
      <button class="modal-confirm" @click="showSuccessModal = false">确定</button>
    </div>
  </div>
</div>
<!-- 清空确认弹窗 -->
<!-- <div v-if="showClearConfirm" class="modal-mask">
  <div class="modal-content">
    <div class="modal-title">是否清空已结算的商品？</div>
    <div class="modal-actions">
      <button class="modal-cancel" @click="handleCancelClear">取消</button>
      <button class="modal-confirm" @click="handleClearSelected">确定</button>
    </div>
  </div>
</div> -->
<!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-mask">
      <div class="modal-content">
        <div class="modal-title">从购物车移除此商品？</div>
        <div class="modal-item">
          <div class="item-img">
            <img :src="itemToDelete?.images" alt="商品图片" />
          </div>
          <div class="item-info">
            <div class="item-title">{{ itemToDelete?.name }}</div>
            <div class="item-attr">
              <span class="color-dot"></span>
              <span>{{ itemToDelete?.colorx }}</span>
              <span class="attr-gap">{{ itemToDelete?.chima }}</span>
            </div>
            <div class="item-price">
              ¥{{ modalPrice * modalNum }} 
            </div>
          </div>
          <div class="item-actions">
            <button class="btn-action" @click="changeModalNum(-1)">-</button>
            <span>{{ modalNum }}</span>
            <button class="btn-action" @click="changeModalNum(1)">+</button>
          </div>
        </div>
        <div class="modal-actions">
          <button class="modal-cancel" @click="cancelDelete">取消</button>
          <button class="modal-confirm" @click="confirmDelete">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cart { padding-bottom: 90px; background: #fafbfc; min-height: 100vh; }
.search-bar { position: sticky; top: 0; z-index: 10; background: #fafbfc; padding: 20px 0 12px 0; }
.search-bar input { width: 92%; margin: 0 auto; display: block; border-radius: 14px; border: none; background: #f3f3f3; padding: 14px 18px; font-size: 16px; color: #aaa; box-shadow: 0 2px 8px #f0f0f0; }
.cart-list { padding: 0 12px; }
.cart-item { display: flex; align-items: center; background: #fff; border-radius: 16px; margin-bottom: 16px; padding: 16px 12px; min-height: 80px; box-shadow: 0 2px 8px #eee; }
.item-img { width: 60px; height: 60px; background: #f3f3f3; border-radius: 10px; margin-right: 10px; display: flex; align-items: center; justify-content: center; overflow: hidden; }
.item-img img { width: 100%; height: 100%; object-fit: cover; }
.item-info { flex: 1; min-width: 0; }
.item-title { font-weight: bold; font-size: 16px; margin-bottom: 6px; color: #222; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item-attr { color: #888; font-size: 14px; margin-bottom: 10px; display: flex; align-items: center; }
.color-dot { display: inline-block; width: 10px; height: 10px; background: #ccc; border-radius: 50%; margin-right: 6px; }
.attr-gap { margin-left: 10px; }
.item-price { color: #222; font-size: 16px; font-weight: bold; }
.item-actions { display: flex; align-items: center; margin-left: 10px; background: #f3f3f3; border-radius: 18px; padding: 2px 8px; }
.btn-action { width: 28px; height: 28px; border: none; background: #f3f3f3; border-radius: 50%; font-size: 18px; color: #222; cursor: pointer; margin: 0 2px; transition: background 0.2s; }
.btn-action:hover { background: #e0e0e0; }
.item-actions span { margin: 0 8px; font-size: 16px; }
.item-delete { margin-left: 10px; font-size: 22px; color: #222; cursor: pointer; transition: color 0.2s; }
.item-delete:hover { color: #ff4d4f; }
.cart-footer { position: fixed; left: 0; right: 0; bottom: 56px; background: #fff; display: flex; justify-content: space-between; align-items: center; padding: 14px 18px; box-shadow: 0 -2px 8px #eee; z-index: 20; }
.total { font-size: 18px; color: #222; text-align: left; }
.total-label { font-size: 14px; color: #888; }
.total-price { font-size: 20px; font-weight: bold; color: #222; }
.checkout { background: #000; color: #fff; border: none; border-radius: 24px; padding: 14px 40px; font-size: 18px; font-weight: bold; box-shadow: 0 2px 8px #eee; }
.modal-mask {
  position: fixed; left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.4);
  display: flex; align-items: center; justify-content: center;
  z-index: 1000;
}
.modal-content {
  background: #fff;
  border-radius: 24px;
  width: 90vw;
  max-width: 400px;
  padding: 24px 16px 16px 16px;
  box-shadow: 0 4px 24px #0001;
  text-align: center;
}
.modal-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 18px;
}
.modal-item {
  display: flex;
  align-items: center;
  background: #fafbfc;
  border-radius: 16px;
  margin-bottom: 18px;
  padding: 12px;
}
.modal-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.modal-cancel, .modal-confirm {
  flex: 1;
  font-size: 18px;
  border: none;
  border-radius: 20px;
  padding: 12px 0;
  margin: 0 8px;
}
.modal-cancel {
  background: #f3f3f3;
  color: #222;
}
.modal-confirm {
  background: #000;
  color: #fff;
}
.item-subtotal {
  color: #ff4d4f;
  font-weight: bold;
}
.cart-toolbar {
  display: flex;
  align-items: center;
  padding: 10px 12px 0 12px;
  background: #fafbfc;
}
.cart-toolbar input[type="checkbox"] {
  margin-right: 8px;
  width: 18px;
  height: 18px;
}
.batch-delete {
  margin-left: 16px;
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 6px 18px;
  font-size: 15px;
  cursor: pointer;
  opacity: 1;
  transition: opacity 0.2s;
}
.batch-delete:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
